﻿using Fibot.Module.K3Cloud.BASE.dto;
using Kingdee.CDP.WebApi.SDK;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace Fibot.Module.K3Cloud.BASE
{
    public class BaseService
    {
        /// <summary>
        /// 业务对象标识
        /// </summary>
        public string formId = "";

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <param name="NeedReturnFields"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public virtual bool Save(object model, List<string> NeedReturnFields, ref string apiResult)
        {
            if (string.IsNullOrEmpty(formId))
            {
                throw new Exception("formId 为空");
            }
            //读取配置，初始化SDK
            K3CloudApi client = new K3CloudApi();
            //请求参数，要求为json字符串
            BaseSaveDto dto = new BaseSaveDto();
            dto.Model = model;
            dto.NeedReturnFields = NeedReturnFields;
            string jsonData = JsonConvert.SerializeObject(dto);
            //调用接口
            var resultJson = client.Save(formId, jsonData);
            apiResult = resultJson;
            //对返回结果进行解析和校验，这里使用的是JsonPatch
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            //判断并记录结果
            if (queryNode == null)
            {
                return false;
            }
            else
            {
                var isSuccess = queryNode.Value<Boolean>();
                return isSuccess;
            }
        }

        /// <summary>
        /// 暂存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public virtual bool Draft(object model)
        {
            if (string.IsNullOrEmpty(formId))
            {
                throw new Exception("formId 为空");
            }
            //读取配置，初始化SDK
            K3CloudApi client = new K3CloudApi();
            //请求参数，要求为json字符串
            BaseSaveDto dto = new BaseSaveDto();
            dto.Model = model;
            string jsonData = JsonConvert.SerializeObject(dto);
            //调用接口
            var resultJson = client.Draft(formId, jsonData);
            //对返回结果进行解析和校验，这里使用的是JsonPatch
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            //判断并记录结果
            if (queryNode == null)
            {
                return false;
            }
            else
            {
                var isSuccess = queryNode.Value<Boolean>();
                return isSuccess;
            }
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public virtual bool Submit(List<string> Numbers)
        {
            if (string.IsNullOrEmpty(formId))
            {
                throw new Exception("formId 为空");
            }

            //读取配置，初始化SDK
            K3CloudApi client = new K3CloudApi();

            //请求参数，要求为json字符串
            BaseSubmitDto dto = new BaseSubmitDto();
            dto.Numbers = Numbers;
            string jsonData = JsonConvert.SerializeObject(dto);

            //调用接口
            var resultJson = client.Submit(formId, jsonData);
            //对返回结果进行解析和校验，这里使用的是JsonPatch
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            //判断并记录结果
            if (queryNode == null)
            {
                return false;
            }
            else
            {
                var isSuccess = queryNode.Value<Boolean>();
                return isSuccess;
            }
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public virtual bool Audit(List<string> Numbers)
        {
            if (string.IsNullOrEmpty(formId))
            {
                throw new Exception("formId 为空");
            }

            //读取配置，初始化SDK
            K3CloudApi client = new K3CloudApi();

            //请求参数，要求为json字符串
            BaseAuditDto dto = new BaseAuditDto();
            dto.Numbers = Numbers;
            string jsonData = JsonConvert.SerializeObject(dto);

            //调用接口
            var resultJson = client.Audit(formId, jsonData);
            //对返回结果进行解析和校验，这里使用的是JsonPatch
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            //判断并记录结果
            if (queryNode == null)
            {
                return false;
            }
            else
            {
                var isSuccess = queryNode.Value<Boolean>();
                return isSuccess;
            }
        }

        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public virtual bool CancelAssign(List<string> Numbers)
        {
            if (string.IsNullOrEmpty(formId))
            {
                throw new Exception("formId 为空");
            }

            //读取配置，初始化SDK
            K3CloudApi client = new K3CloudApi();

            //请求参数，要求为json字符串
            BaseCancelAssignDto dto = new BaseCancelAssignDto();
            dto.Numbers = Numbers;
            string jsonData = JsonConvert.SerializeObject(dto);

            //调用接口
            var resultJson = client.CancelAssign(formId, jsonData);
            //对返回结果进行解析和校验，这里使用的是JsonPatch
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            //判断并记录结果
            if (queryNode == null)
            {
                return false;
            }
            else
            {
                var isSuccess = queryNode.Value<Boolean>();
                return isSuccess;
            }
        }

        /// <summary>
        /// 反审核
        /// </summary>
        /// <param name="Numbers"></param>
        /// <returns></returns>
        public virtual bool UnAudit(List<string> Numbers)
        {
            if (string.IsNullOrEmpty(formId))
            {
                throw new Exception("formId 为空");
            }

            //读取配置，初始化SDK
            K3CloudApi client = new K3CloudApi();

            //请求参数，要求为json字符串
            BaseUnAuditDto dto = new BaseUnAuditDto();
            dto.Numbers = Numbers;
            string jsonData = JsonConvert.SerializeObject(dto);

            //调用接口
            var resultJson = client.UnAudit(formId, jsonData);
            //对返回结果进行解析和校验，这里使用的是JsonPatch
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            //判断并记录结果
            if (queryNode == null)
            {
                return false;
            }
            else
            {
                var isSuccess = queryNode.Value<Boolean>();
                return isSuccess;
            }

        }

        public virtual JObject View(int createOrgId, string number)
        {
            K3CloudApi client = new K3CloudApi();
            BaseViewDto dto = new BaseViewDto()
            {
                CreateOrgId = createOrgId,
                Number = number,
                Id = "",
                IsSortBySeq = false
            };
            string jsonData = JsonConvert.SerializeObject(dto);
            var resultJson = client.View(formId, jsonData);
            //对返回结果进行解析和校验，这里使用的是JsonPatch
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");
            //判断并记录结果
            if (queryNode == null)
            {
                return null;
            }
            else
            {
                var isSuccess = queryNode.Value<Boolean>();
                if (isSuccess)
                {
                    return resultJObject.SelectToken("$.Result").Value<JObject>();
                }
                else
                {
                    return null;
                }
            }
        }

        public List<List<object>> ExecuteBillQuery(string FieldKeys, string FilterString, string OrderString, int Limit)
        {
            BaseExecuteBillQueryDto dto = new BaseExecuteBillQueryDto()
            {
                FormId = this.formId,
                FieldKeys = FieldKeys,
                FilterString = FilterString,
                OrderString = OrderString,
                TopRowCount = 10,
                StartRow = 0,
                Limit = Limit,
                SubSystemId = ""
            };

            K3CloudApi client = new K3CloudApi();
            string jsonData = JsonConvert.SerializeObject(dto);
            var resultJson = client.ExecuteBillQuery(jsonData);
            //返回的数据类型为List<List<object>>，错误的返回结果只有一行数据且IsSuccess为False      
            if (resultJson.Count == 1)
            {
                //对返回结果进行解析和校验，这里使用的是JsonPatch
                var resultJObject = JArray.Parse(JsonConvert.SerializeObject(resultJson[0]));
                var queryNode = resultJObject.SelectToken("$..IsSuccess");
                if (queryNode != null)
                {
                    var isSuccess = queryNode.Value<Boolean>();
                    return null;
                }
                else
                {
                    return resultJson;
                }
            }
            else
            {
                return resultJson;
            }
        }
    }
}